<?php

$app->get('/extra/imageOfTheDay', 'getImageOfTheDay');
$app->get('/extra/statistic', 'getStatistic');
$app->get('/extra/allPictures/:page', 'printAllPictures');
// $app->get('/extra/resizePictures/', 'resizePictures');

function getImageOfTheDay() {
	$picture = getPictureOfTheDay();

	$sectionData = base64_decode($picture->section);
	\Slim\Slim::getInstance()->contentType('image/png');
	echo $sectionData;
}

function getPictureOfTheDay() {
	$day = date("zY");
	$sqlQuery = createPictureSelect("de")." ORDER BY RAND($day) LIMIT 1";
	return doGetSinglePicture($sqlQuery);
}

function getStatistic() {
	$statistic = getPictureCountForEachLanguage();
	$statistic['photographers'] = getPhotographersCount();
	$statistic['version'] = getApplicationVersion();
	$statistic['supportedLanguages'] = getSupportedLanguagesArray();
	echo json_encode($statistic);
}

function getPictureCountForEachLanguage() {
	$sqlCount = "";
	foreach (getSupportedLanguagesArray() as $language) {
		if ($sqlCount != "")
		$sqlCount = $sqlCount.", ";
		$sqlCount = $sqlCount."COUNT(NULLIF(TRIM(correctAnswers_$language), '')) as $language";
	}
	$sqlQuery = "SELECT $sqlCount FROM ".TABLE_PICTURE;
	$sql = createQuery($sqlQuery);

	$result = mysqli_fetch_object($sql);
	$array = array();
	foreach (getSupportedLanguagesArray() as $language) {
		$array["count_$language"] = $result->$language;
	}
	return $array;
}

function getPhotographersCount() {
	$sqlQuery = "SELECT COUNT(DISTINCT photographer) AS count FROM ".TABLE_PICTURE;
	$sql = createQuery($sqlQuery);
	return mysqli_fetch_object($sql)->count;
}

function printAllPictures($page) {
	echo "<table border='0'>\n";
	echo "<tr><th>Bildausschnitt</th><th>Bild</th><th>Richtig</th><th>Beschreibung</th></tr>";

	$size = 100;
	$sql = createQuery(createFullManagerPictureSelect()." ORDER BY id ASC LIMIT ".($page*20).", 20");
	while ($result = mysqli_fetch_object($sql)) {
		echo "<tr>";
		echo "<td><img src='data:image/png;base64,".$result->section."' width='$size' height='$size' /></td>";
		if ($result->bigPicture != null) {
			echo "<td><img src='data:image/png;base64,".$result->bigPicture."' width='$size' height='$size' /></td>";
		} else {
			echo "<td></td>";
		}
		echo "<td>";
		foreach (getSupportedLanguagesArray() as $language) {
			$variable = "correctAnswers_$language";
			echo $result->$variable."<br>";
		}
		echo "</td>";

		echo "<td>";
		foreach (getSupportedLanguagesArray() as $language) {
			$variable = "description_$language";
			echo $result->$variable."<br>";
		}
		echo "</td>";

		echo "</tr>";
	}
	echo "</table>\n";
}

/*
 *
*/

function resizePictures() {
	$sql = createQuery(createFullManagerPictureSelect());
	while ($picture = mysqli_fetch_object($sql)) {
		resizePicture($picture);
	}
}

function resizePicture($picture) {
	echo "<b>".$picture->correctAnswers_de.":</b> ";

	$resizedSection = resizePictureData($picture->section, "section");
	$bigPictureSection = resizePictureData($picture->bigPicture, "bigPicture");

	if ($resizedSection != null || $bigPictureSection != null)
		updateDataBaseAfterResizing($picture, $resizedSection, $bigPictureSection);

	echo "<br>";
}

function resizePictureData($pictureData, $imageType) {
	if ($pictureData == null || "" == $pictureData)
		return null;
	$data = base64_decode($pictureData);
	$image = imagecreatefromstring($data);
	if ($image !== false) {
		return resizeImageDataIfNecessary($image, $imageType);
	}
	// echo "An error occurred while creating $imageType.";
	return null;
}

function resizeImageDataIfNecessary($image, $imageType) {
	$width = imagesx($image);
	$height = imagesy($image);
	$maxSize = 500;
	if ($width <= $maxSize && $height <= $maxSize) {
// 		echo "No resizing of $imageType necessary.";
		return null;
	}
	$shrinkPercent = min($maxSize / $width, $maxSize / $height);
	return resizeImageData($image, $shrinkPercent, $imageType);
}

function resizeImageData($source, $shrinkPercent, $imageType) {
	$width = imagesx($source);
	$height = imagesy($source);
	$newWidth = $width * $shrinkPercent;
	$newHeight = $height * $shrinkPercent;
	$shrunkImage = imagecreatetruecolor($newWidth, $newHeight);
	imagecopyresized($shrunkImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
	// echo "Shrunk $imageType by ".round($shrinkPercent * 100)."%. ";
	return $shrunkImage;
}

function updateDataBaseAfterResizing($picture, $resizedSection, $bigPictureSection) {
	$sectionData = getStringFromImageResource($resizedSection);
	$bigPictureData = getStringFromImageResource($bigPictureSection);
	$setClause = getPictureSqlSetClause(array(), $sectionData, $bigPictureData);
	mysqli_query("UPDATE ".TABLE_PICTURE." SET $setClause WHERE id = ".$picture->id);
	echo "Updated database. $sectionData";
}

function getStringFromImageResource($resource) {
	if ($resource == null)
		return null;
	ob_start();
	imagejpeg($resource);
	$contents =  ob_get_contents();
	ob_end_clean();
	return base64_encode($contents);
}

?>
